using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Web.UI;
using System.ComponentModel;
using System.Globalization;
using System.Web;

namespace RealWorld.Grids
{
    public class FrozenGridView : GridView
    {
        private int _i = 0; // MNB added used to add id's to rows
        
        private const string FrozenTopCssClass = "frozenTop";

        //MNB add
        Color _MouseOverColor = Color.Navy;
        Color _TextOverColor = Color.White;
        Color _SelectedRowColor = Color.Blue;
        Color _SelectedRowTextColor = Color.White;
        //MNB end


        #region Properties

        [Browsable(true), DefaultValue(true), Category("Behavior"), DisplayName("Freeze Header")]
        public bool FreezeHeader
        {
            get
            {
                object val = this.ViewState["FreezeHeader"];
                if (null == val)
                {
                    return true;
                }

                return (bool)val;
            }
            set
            {
                this.ViewState["FreezeHeader"] = value;
            }
        }

        [Browsable(true), DefaultValue(ScrollBars.None), Category("Behavior")]
        public ScrollBars Scrolling
        {
            get
            {
                object val = this.ViewState["Scrolling"];
                if (null == val)
                {
                    return ScrollBars.None;
                }

                return (ScrollBars)val;
            }
            set
            {
                this.ViewState["Scrolling"] = value;
            }
        }
        
        public string RowCssClass
        {
            get
            {
                string rowClass = (string)ViewState["rowClass"];
                if (!string.IsNullOrEmpty(rowClass))
                    return rowClass;
                else
                    return string.Empty;
            }
            set
            {
                ViewState["rowClass"] = value;
            }
        }
        
        public string HoverRowCssClass
        {
            get
            {
                string hoverRowClass = (string)ViewState["hoverRowClass"];
                if (!string.IsNullOrEmpty(hoverRowClass))
                    return hoverRowClass;
                else
                    return string.Empty;
            }
            set
            {
                ViewState["hoverRowClass"] = value;
            }
        }

        public Unit ScrollWidth
        {
            get
            {
                return base.Width;
            }
            set
            {
                base.Width = value;
            }
        }

        public override Unit Width
        {
            get
            {
                object val = this.ViewState["DivWidth"];
                if (null == val)
                {
                    return Unit.Empty;
                }

                return (Unit)val;
            }
            set
            {
                this.ViewState["DivWidth"] = value;
            }
        }

        public Unit ScrollHeight
        {
            get
            {
                return base.Height;
            }
            set
            {
                base.Height = value;
            }
        }

        public override Unit Height
        {
            get
            {
                object val = this.ViewState["DivHeight"];
                if (null == val)
                {
                    return Unit.Empty;
                }

                return (Unit)val;
            }
            set
            {
                this.ViewState["DivHeight"] = value;
            }
        }

        private string OverflowX
        {
            get
            {
                if (this.Scrolling == ScrollBars.Horizontal || this.Scrolling == ScrollBars.Both)
                {
                    return "scroll";
                }
                else if (this.Scrolling == ScrollBars.Auto)
                {
                    return "auto";
                }
                else
                {
                    return "visible";
                }
            }
        }

        private string OverflowY
        {
            get
            {
                if (this.Scrolling == ScrollBars.Vertical || this.Scrolling == ScrollBars.Both)
                {
                    return "scroll";
                }
                else if (this.Scrolling == ScrollBars.Auto)
                {
                    return "auto";
                }
                else
                {
                    return "visible";
                }
            }
        }
        //MNB add
        public Color MouseOverColor
        {
            get { return _MouseOverColor; }
            set { _MouseOverColor = value; }
        }

        public Color TextOverColor
        {
            get { return _TextOverColor; }
            set { _TextOverColor = value; }
        }

        public Color SelectedRowColor
        {
            get { return _SelectedRowColor; }
            set { _SelectedRowColor = value; }
        }

        public Color SelectedRowTextColor
        {
            get { return _SelectedRowTextColor; }
            set { _SelectedRowTextColor = value; }
        }
        //MNB end


        #endregion

        private static readonly object RowClickedEventKey = new object();

        public event GridViewRowClicked RowClicked;

        protected virtual void OnRowClicked(GridViewRowClickedEventArgs e)
        {
            if (RowClicked != null)
                RowClicked(this, e);
        }

        #region Overrides


        protected override void CreateChildControls()
        {
            base.CreateChildControls();

        }

        protected override void RaisePostBackEvent(string eventArgument)
        {
            if (eventArgument.StartsWith("rc"))
            {
                int index = Int32.Parse(eventArgument.Substring(2));
                GridViewRowClickedEventArgs args = new GridViewRowClickedEventArgs(Rows[index]);
                OnRowClicked(args);
            }
            else
                base.RaisePostBackEvent(eventArgument);
        }

        protected override void PrepareControlHierarchy()
        {
            base.PrepareControlHierarchy();

            for (int i = 0; i < Rows.Count; i++)
            {
                string argsData = "rc" + Rows[i].RowIndex.ToString();
                Rows[i].Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(this, argsData));

                if (RowCssClass != string.Empty)
                    Rows[i].Attributes.Add("onmouseout", "this.className='" + RowCssClass + "';");

                if (HoverRowCssClass != string.Empty)
                    Rows[i].Attributes.Add("onmouseover", "this.className='" + HoverRowCssClass + "';");
                
                //MNB Added
                Rows[i].Style.Add("cursor", "pointer");

            }
        }

        protected override void OnDataBound(EventArgs e)
        {
            base.OnDataBound(e);

            this.FreezeCells();

        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (this.FreezeHeader && !this.Page.Items.Contains(FrozenGridView.FrozenTopCssClass))
            {
                this.Page.Items[FrozenGridView.FrozenTopCssClass] = "1";
                FrozenTopStyle frozenTopStyle = new FrozenTopStyle();
                this.Page.Header.StyleSheet.CreateStyleRule(frozenTopStyle, null, "." + FrozenGridView.FrozenTopCssClass);
            }
            //MNB add
            //string resourceName = "RealWorld.Grids.GridViewScript.js";

            //ClientScriptManager cs = this.Page.ClientScript;
            //cs.RegisterClientScriptResource(typeof(RealWorld.Grids.FrozenGridView), resourceName);
            //MNB end
        }

        //MNB add
        protected override void OnRowCreated(GridViewRowEventArgs e)
        {


            base.OnRowCreated(e);
            GridViewRow row = e.Row;
            Color bgColor = Color.Empty;
            Color color = Color.Empty;

            //if (row.RowIndex % 2 == 0)
            //{
            //    bgColor = (this.RowStyle.BackColor == Color.Empty) ? Color.White : this.RowStyle.BackColor;
            //    color = (this.RowStyle.ForeColor == Color.Empty) ? Color.Black : this.RowStyle.ForeColor;
            //}
            //else
            //{
            //    bgColor = (this.AlternatingRowStyle.BackColor == Color.Empty) ? Color.White : this.AlternatingRowStyle.BackColor;
            //    color = (this.AlternatingRowStyle.ForeColor == Color.Empty) ? Color.Black : this.AlternatingRowStyle.ForeColor;
            //}
            if (row.RowType == DataControlRowType.DataRow)
            {
                //row.Attributes.Add("onmouseover", String.Format("MouseEnter(this,'{0}','{1}')",
                //    ColorTranslator.ToHtml(this.MouseOverColor),
                //    ColorTranslator.ToHtml(this.TextOverColor)));
                //row.Attributes.Add("onmouseout", "MouseLeave(this)");
                row.Attributes.Add("onmousedown", String.Format("MouseDown(this,'{0}','{1}')",
                    ColorTranslator.ToHtml(this.SelectedRowColor),
                    ColorTranslator.ToHtml(this.SelectedRowTextColor)));
                row.Attributes.Add("OriginalColor", ColorTranslator.ToHtml(bgColor));
                row.Attributes.Add("OriginalTextColor", ColorTranslator.ToHtml(color));
                row.Attributes.Add("id", _i.ToString());
                _i++;
               
            }
        }
        //MNB end

        protected override void Render(HtmlTextWriter writer)
        {
            if (this.Page != null)
            {
                this.Page.VerifyRenderingInServerForm(this);
            }
            this.PrepareControlHierarchy();
            if (!this.DesignMode)
            {
                string clientID = this.ClientID;
                if (clientID == null)
                {
                    throw new HttpException("FrozenGridView Must Be Parented");
                }

                writer.AddAttribute(HtmlTextWriterAttribute.Id, String.Format(CultureInfo.InvariantCulture, "__gv{0}__div", clientID), true);

                writer.AddStyleAttribute(HtmlTextWriterStyle.OverflowX, this.OverflowX);
                writer.AddStyleAttribute(HtmlTextWriterStyle.OverflowY, this.OverflowY);
                if (!this.Width.IsEmpty)
                {
                    writer.AddStyleAttribute(HtmlTextWriterStyle.Width, this.Width.ToString(CultureInfo.InvariantCulture));
                }
                if (!this.Height.IsEmpty)
                {
                    writer.AddStyleAttribute(HtmlTextWriterStyle.Height, this.Height.ToString(CultureInfo.InvariantCulture));
                }
                writer.AddStyleAttribute(HtmlTextWriterStyle.Position, "relative");
                writer.AddStyleAttribute(HtmlTextWriterStyle.BorderColor, "Black");
                writer.AddStyleAttribute(HtmlTextWriterStyle.BorderWidth, "1px");
                writer.AddStyleAttribute(HtmlTextWriterStyle.BorderStyle, "solid");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
            }
            this.RenderContents(writer);
            if (!this.DesignMode)
            {
                writer.RenderEndTag();

            }
        }

        #endregion

        private void FreezeCells()
        {
            if (this.FreezeHeader)
            {
                foreach (DataControlFieldHeaderCell th in this.HeaderRow.Cells)
                {
                    th.CssClass = FrozenGridView.FrozenTopCssClass + " " + th.CssClass;
                }
            }
        }

        private class FrozenTopStyle : Style
        {
            internal FrozenTopStyle()
            {
            }

            protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver)
            {
                base.FillStyleAttributes(attributes, urlResolver);

                attributes[HtmlTextWriterStyle.Top] = "expression(this.offsetParent.scrollTop)";
                attributes[HtmlTextWriterStyle.Position] = "relative";
                attributes[HtmlTextWriterStyle.ZIndex] = "2";
            }
        }
    }
    public class GridViewRowClickedEventArgs : EventArgs
    {
        private GridViewRow _row;

        public GridViewRowClickedEventArgs(GridViewRow aRow)
            : base()
        {
            _row = aRow;
        }

        public GridViewRow Row
        {
            get
            { return _row; }
        }
    }

    public delegate void GridViewRowClicked(object sender, GridViewRowClickedEventArgs args);
}
